package com.wxtf.platform.plugins.org;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: OrgAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.org</li>
 * <li>Description: 组织机构</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 16, 2012 1:37:58 PM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class OrgAction extends LogicBase implements CommonsCallProvider {
	private static Log log = LogFactory.getLog(OrgAction.class);

	public OrgAction(String jsonArray) {

	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getExtendData());
				return msg.toString();
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
				return msg.toString();
			} else if ("update".equals(this.getMethodName())) {// 修改
				msg = this.update(this.getLogicData());
				return msg.toString();
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else if ("listUser".equals(this.getMethodName())) {
				msg = this.listUser(this.getLogicData());
				return msg.toString();
			} else if ("saveUser".equals(this.getMethodName())) {
				msg = this.saveUser(this.getLogicData());
			} else if ("delUser".equals(this.getMethodName())) {
				msg = this.delUser(this.getLogicData());
			} else if ("listOrg".equals(this.getMethodName())) {//人所在的部门列表
				msg = this.listOrg(this.getLogicData());
				return msg;
			} else if ("listOrg4App".equals(this.getMethodName())) {//根据当前登录人列出所有机构
				msg = this.listOrg4App(this.getLogicData());
				return msg;
			} else if ("listOrgByPid".equals(this.getMethodName())) {//根据父ID获取直接子节点
				msg = this.listOrgByPid(this.getLogicData());
				return msg;
			} else if ("listUser4Org".equals(this.getMethodName())) {
				msg = this.listUser4Org(this.getExtendData());
				return msg.toString();
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	@Override
	public Object select(Object jsonArray) throws Exception {
		List<Map<String,Object>> list =  AccessDataBaseUtil.query4ListMap(fields, sql, new Object[] { "0" });
		list = this.getOrgByPid(list);
		JSONArray array = JSONArray.fromObject(list);
		String msg = "{\"Rows\":"+array.toString()+"}";
		return msg;
	}

	private String[] fields = { "id", "dparent_id", "text", "logic_code", "action", "ordernum", "director_name", "director_phone", "director_mobile", "director_email", "levels"};
	private String sql = "select department_id,dparent_id,caption,logic_code,action, ordernum,director_name,director_phone,director_mobile,director_email,levels from t_department where dparent_id = ? order by ordernum";
	private List<Map<String,Object>> getOrgByPid(List<Map<String,Object>> list) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		for(Map<String,Object> map: list){
			String id = String.valueOf(map.get("id"));
			List<Map<String,Object>> list1 = AccessDataBaseUtil.query4ListMap(fields, sql, new Object[] { id });
			map.put("children", list1);
			map.put("sons", list1.size());
			this.getOrgByPid(list1);
		}
		return list;
	}
	
	/** 
	 * 描述：listOrg 人选部门时的部门列表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 19, 2012  3:38:12 PM
	 * @author chun_chang
	 */
	public Object listOrg(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("user_id");
		String name = jsonObject.getString("name");//组名称
		
		//将已经选中的组id放入集合中
		String sql = "select department_id from t_user_department where user_id = ?";
		List<Object> list1 = AccessDataBaseUtil.query4List(sql, new Object[] { id });
		Set<String> set = new HashSet<String>();
		for (Object o : list1) {
			set.add(String.valueOf(o));
		}
		
		String sql1 = "select department_id, caption,'' from t_department where dparent_id = ?";
		if (StringUtils.isNotBlank(name)) {
			sql1 += " and caption like '%" + name + "%'";
		}
		
		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(fields2, sql1, new Object[] { "0" });
		for (Map<String, Object> map : list) {
			String groupId = String.valueOf(map.get("id"));
			if (set.add(groupId)) {
				set.remove(groupId);
			} else {
				map.put("oth_id", id);
				map.put("ischecked",true);
			}
		}
		list = this.getOrgByPid1(list, sql1, set, "0");
		
		if(list!=null){
			array = JSONArray.fromObject(list);
			return array.toString();
		}else{
			return "[]";
		}
		
	}
	
	private String[] fields2 = { "id", "text", "oth_id" };
	private List<Map<String, Object>> getOrgByPid1(List<Map<String, Object>> list, String sql, Set<String> set, String id1) throws Exception {
		if (null == list || list.size() <= 0) {
			return null;
		}
		for (Map<String, Object> map : list) {
			String id = String.valueOf(map.get("id"));
			List<Map<String, Object>> list1 = AccessDataBaseUtil.query4ListMap(fields2, sql, new Object[] { id });
			for (Map<String, Object> map1 : list1) {
				String groupId = String.valueOf(map1.get("id"));
				if (set.add(groupId)) {
					set.remove(groupId);
				} else {
					map1.put("oth_id", id);
					map1.put("ischecked",true);
				}
			}
			map.put("children", list1);
			this.getOrgByPid1(list1, sql, set, id);
		}
		return list;
	}
	
	
	/** 
	 * 描述：listOrg4App 根据当前登录人列出所有机构
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Aug 22, 2012  10:31:43 AM
	 * @author chun_chang
	 */
	private String[] jsonField = { "id", "text" };
	public Object listOrg4App(Object jsonArray) throws Exception {
//		UserBean user = (UserBean) this.getRequest().getSession().getAttribute("userBean");
//		String userId = user.getUserId();
//		if("0".equals(userId)){
			sql = "select DEPARTMENT_ID, CAPTION from T_DEPARTMENT where DPARENT_ID = ?";
//		} else {
//			sql = "select r.DEPARTMENT_ID, r.CAPTION from T_DEPARTMENT r,T_USER_DEPARTMENT s where r.DEPARTMENT_ID = s.DEPARTMENT_ID and r.DPARENT_ID = ? and s.USER_ID = '" + userId + "'";
//		}
		Object[] param = { "0" };
		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(jsonField, sql, param);
		
		list = this.getOrgByPid3(list, sql);
		if(list == null) {
			return "[]";
		} else {
			JSONArray array = JSONArray.fromObject(list);
			return array.toString();
		}
	}
	private List<Map<String, Object>> getOrgByPid3(List<Map<String, Object>> list, String sql) throws Exception {
		if(null == list || list.size() <= 0) {
			return null;
		}
		for(Map<String, Object> map: list) {
			String id = String.valueOf(map.get("id"));
			List<Map<String, Object>> list1 = AccessDataBaseUtil.query4ListMap(jsonField, sql, new Object[] { id });
			map.put("children", list1);
			this.getOrgByPid3(list1, sql);
		}
		return list;
	}
	
	/** 
	 * 描述：listOrgByPid 根据父ID获取直接子节点
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Aug 22, 2012  2:53:23 PM
	 * @author chun_chang
	 */
	public Object listOrgByPid(Object jsonArray) throws Exception {
		UserBean user = (UserBean) this.getRequest().getSession().getAttribute("userBean");
		String userId = user.getUserId();
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String pid = jsonObject.getString("pid");
		
		Object[] param = null;
		if("0".equals(userId)){
			sql = "select DEPARTMENT_ID, CAPTION from T_DEPARTMENT where DPARENT_ID = ?";
			param = new Object[]{ pid };
		} else {
			sql = "select r.DEPARTMENT_ID, r.CAPTION from T_DEPARTMENT r,T_USER_DEPARTMENT s where r.DEPARTMENT_ID = s.DEPARTMENT_ID and r.DPARENT_ID = ? and s.USER_ID = ?";
			param = new Object[]{ pid, userId };
		}
		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(jsonField, sql, param);
		
		if(list == null) {
			return "[]";
		} else {
			array = JSONArray.fromObject(list);
			return array.toString();
		}
	}
	
	
	@Override
	public Object insert(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
		}
		obj[0] = AccessDataBaseUtil.getPKUUID();
		
		String sql = "select count(*) from t_department where dparent_id = ? and caption = ?";
		int cnt = AccessDataBaseUtil.queryForInt(sql, new Object[] { obj[1], obj[2] });
		if(cnt > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"部门名称重复\"}";
		}
		
		sql = "select count(*) from t_department where dparent_id = ? and logic_code = ?";
		cnt = AccessDataBaseUtil.queryForInt(sql, new Object[] { obj[1], obj[3] });
		if(cnt > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"部门简码重复\"}";
		}
		sql = "insert into t_department(department_id,dparent_id,caption,logic_code,action, ordernum,director_name,director_phone,director_mobile,director_email,levels) values" +
				"('" + obj[0] + "','" + obj[1] + "','" + obj[2] + "','" + obj[3] + "','" + obj[4] + "'," + obj[5] + "," +
				"'" + obj[6] + "','" + obj[7] + "','" + obj[8] + "','" + obj[9] + "'," + obj[10] + ")";
		
		//在该机构下新建默认用户
		String levels = obj[10].toString();
		String curTime = FormatUtil.getCurentDateTime();
		String newUserId = AccessDataBaseUtil.getPKUUID();
		String orgName = obj[2].toString();
		String loginSql = "select count(*) from t_department where caption = ? ";
		List<Object> ls = AccessDataBaseUtil.query4List(loginSql, new Object[] { orgName });
		int hasId = Integer.parseInt(ls.get(0).toString());
		if(hasId > 0){
			String sql3 = "select caption from t_department where department_id = ?";
			List<Object> list = AccessDataBaseUtil.query4List(sql3, new Object[] { obj[1] });
			orgName = list.get(0).toString() + "_" + orgName;
		}
		String sql1 = "insert into T_USER(USER_ID,uparent_id,caption,action) values('" + newUserId + "','0','" + orgName + "','" + orgName + "')";
		String sql2 = "INSERT INTO T_USER_INFO(user_id,user_status,real_name,user_passwd,user_modified,user_sex,user_education) VALUES ('" + newUserId + "','1','Aqua','"+AccessDataBaseUtil.getKey()+"','" + curTime + "','N','index.jsp')";
		String sql3 = "";
		// 为默认用户赋角色
		switch(Integer.valueOf(levels)){
			case 1:
				sql3 = "insert into T_USER_ROLE(U_R_ID,USER_ID,ROLE_ID) values('" + AccessDataBaseUtil.getPKUUID() + "','" + newUserId + "','ee20461160ca49b79738423b64353a69')";
				break;
			case 2:
				sql3 = "insert into T_USER_ROLE(U_R_ID,USER_ID,ROLE_ID) values('" + AccessDataBaseUtil.getPKUUID() + "','" + newUserId + "','6de5df675d0545f99b06d7a580c71f27')";
				break;
			case 3:
				sql3 = "insert into T_USER_ROLE(U_R_ID,USER_ID,ROLE_ID) values('" + AccessDataBaseUtil.getPKUUID() + "','" + newUserId + "','5a9f382dc8764d9a861e79b58268dd3a')";
				break;
			default:
				return "{\"result\":false,\"resultmessage\":\"\",\"resultrecord\":\"不能添加一级机构\"}";
		}
		String sql5 = "insert into T_USER_ROLE(U_R_ID,USER_ID,ROLE_ID) values('" + AccessDataBaseUtil.getPKUUID() + "','" + newUserId + "','1')";
		String sql4 = "insert into T_USER_DEPARTMENT(U_D_ID,DEPARTMENT_ID,USER_ID)values('" + AccessDataBaseUtil.getPKUUID() + "','" + obj[0] + "','" + newUserId + "')";
		
		String[] sqls = { sql, sql1, sql2, sql3, sql5, sql4 };
		AccessDataBaseUtil.executeSQLUpdate(sqls);
		return "{\"result\":true,\"resultmessage\":\"调用成功\",\"resultrecord\":\"保存成功\"}";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length - 1];
		for (int j = 0; j < fields.length - 1; j++) {
			if(j == fields.length - 2) {
				//为了过滤levels，因为不需要更新这个字段
				continue;
			}
			obj[j] = jsonObject.getString(fields[j+1]);
		}
		obj[obj.length - 1] = jsonObject.getString(fields[0]);
		
		String sql = "select count(*) from t_department where dparent_id = ? and department_id <> ? and caption = ?";
		int cnt = AccessDataBaseUtil.queryForInt(sql, new Object[] { obj[0], obj[obj.length - 1], obj[1] });
		if(cnt > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"部门名称重复\"}";
		}
		
		sql = "select count(*) from t_department where dparent_id = ? and department_id <> ? and logic_code = ?";
		cnt = AccessDataBaseUtil.queryForInt(sql, new Object[] { obj[0], obj[obj.length - 1], obj[2] });
		if(cnt > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"部门简码重复\"}";
		}
		
		sql = "update t_department set dparent_id = ?,caption = ?,logic_code = ?,action = ?, ordernum = ?,director_name = ?,director_phone = ?,director_mobile = ?,director_email = ? where department_id = ?";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		
		return "{\"result\":true,\"resultmessage\":\"调用成功\",\"resultrecord\":\"修改成功\"}";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		List<Object> list = new ArrayList<Object>();
		for(String id1: ids){
			list.add(id1);
		}
		List<Object> list1 = this.getOrgIdsByPids(list);
		list1.addAll(list);
		
		StringBuffer sql = new StringBuffer("delete from t_department where department_id in ('");
		StringBuffer sql1 = new StringBuffer("delete from t_user_department where department_id in ('");
		
		for(Object id2: list1){
			sql.append(id2).append("','");
			sql1.append(id2).append("','");
		}
		sql.delete(sql.length() - 3, sql.length() - 1).append(")");
		sql1.delete(sql.length() - 3, sql1.length() - 1).append(")");
		
		String[] sqls = { sql1.toString(), sql.toString() };
		AccessDataBaseUtil.executeSQLUpdate(sqls);
		return "\"删除成功\"";
	}
	private String sql1 = "select department_id from t_department where dparent_id = ?";
	private List<Object> getOrgIdsByPids(List<Object> list) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		List<Object> list2 = new ArrayList<Object>();
		for(Object obj: list){
			List<Object> list1 = AccessDataBaseUtil.query4List(sql1, new Object[] { obj });
			if(null != list1 && list1.size() > 0){
				List<Object> list3 = this.getOrgIdsByPids(list1);
				list2.addAll(list1);
				list2.addAll(list3);
			}
		}
		return list2;
	}

	/** 
	 * 描述：listUser 部门选人时，人员列表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 19, 2012  3:42:10 PM
	 * @author chun_chang
	 */
	public Object listUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String orgId = jsonObject.getString("orgId");
		String userName = jsonObject.getString("userName");
		String jigou = jsonObject.getString("jigou");
		sql = " from t_user r where r.user_id not in ( select t.user_id from t_user_department t, t_department s WHERE t.department_id = s.department_id and t.department_id = ?) ";
		if(StringUtils.isNotBlank(jigou)){
			sql += " and r.user_id in( select t.user_id from t_user_department t,t_department s where t.department_id = s.department_id and s.caption like '%" + jigou + "%') ";
		}
		if (StringUtils.isNotBlank(userName)) {
			sql += " and r.caption like '%" + userName + "%'";
		}
		String countSql = "select count(*)" + sql;
		String querySql = "select r.user_id,r.caption" + sql + " order by r.caption";
		String[] fields = { "user_id", "caption"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{ orgId });
	}
	
	public Object saveUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String orgId = jsonObject.getString("orgId");
		String userIds = jsonObject.getString("userId");
		String[] userId = userIds.split(",");
		
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		
		sql = "delete from t_user_department where department_id = '" + orgId + "' and USER_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql,userId);
		
		buff.setLength(0);
		for (String id1 : userId) {
			buff.append("insert into t_user_department(u_d_id,department_id,user_id)")
				.append("values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("',")
				.append("'").append(orgId).append("',")
				.append("'").append(id1).append("'")
				.append(")");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
	
	public Object delUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String orgId = jsonObject.getString("orgId");
		String userIds = jsonObject.getString("userId");
		String[] userId = userIds.split(",");
		
		sql = "delete from t_user_department where department_id = '" + orgId + "' and USER_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql,userId);
		return "\"删除成功\"";
	}
	
	public Object listUser4Org(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		
		String id = jsonObject.getString("orgId");
		String userName = jsonObject.getString("userName");
		sql = " from t_user r,t_user_department s,t_department d where r.user_id = s.user_id and s.department_id = d.department_id and s.department_id = ?";
		if (userName != null && !"".equals(userName)) {
			sql += " and r.caption like '%" + userName + "%'";
		}
		String countSql = "select count(1)" + sql;
		String querySql = "select r.user_id, r.caption" + sql + " order by r.caption";
		String[] fields = { "user_id", "caption"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{ id });
	}
	
	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}
}
